import { JSB } from "cc/env";
import { lobby } from "../lobby";

type HttpType = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
/**
 * 网络请求
 */
export default class HttpClient {
    public static host: string = "http://14.103.154.32:8002/api/";//'http://118.89.123.3:8080';//116.62.119.201:3000;https://dingdang.haidiao888.com
    private static instance: HttpClient = null!;

    private static uid: number = 0;
    private static token: string = null!;
    private constructor() { }

    public static getInstance(): HttpClient {
        if (!this.instance) {
            this.instance = new HttpClient();
        }
        return this.instance;
    }
    public setToken(token: string) {
        HttpClient.token = token;
    }
    public setUid(uid: number) {
        HttpClient.uid = uid;
    }

    requestAsync(type: HttpType, uri: string, param?: any, pathArg: string | number | null = null!) {
        return new Promise<any>((rs, rj) => {
            let callback = (res: any) => {
                rs(res)
            }
            let error_cb = (res: any) => {
                rj(res)
            }
            this.request(type, uri, param, pathArg, callback, error_cb)
        })
    }
    /**
     * @param type method
     * @param uri path
     * @param param data
     * @param pathArg 路径参数
     * @param cb callback
     */
    public request(type: HttpType, uri: string, param?: any, pathArg: string | number | null = null!, cb?: Function, error_cb?: Function) {
        // return new Promise<any>((rs, rj) => {
        let requestURL = HttpClient.host + uri + (pathArg ? `/${pathArg}` : '');
        let xhr = new XMLHttpRequest();
        xhr.timeout = 5000;
        let jsonData = param ? JSON.stringify(param) : null;
        if (type === 'GET') {
            if (param) {
                let dataStr = ''; //数据拼接字符串
                Object.keys(param).forEach(key => {
                    dataStr += key + '=' + param[key] + '&';
                })
                if (dataStr !== '') {
                    dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
                    requestURL = requestURL + '?' + dataStr;
                }
            }
        }
        xhr.open(type, requestURL, true);
        if (HttpClient.uid) {
            xhr.setRequestHeader("uid", HttpClient.uid.toString());
        }
        if (HttpClient.token) {
            xhr.setRequestHeader("world-access-token", HttpClient.token);
        }
        if (type != "GET") {
            xhr.setRequestHeader('Content-Type', 'application/json');
        }


        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                let res = null;
                try {
                    res = JSON.parse(xhr.response);
                    console.log(res);
                    if (xhr.status >= 200 && xhr.status < 300) {
                        if (res.code == 0) {
                            if (cb && typeof cb == 'function') {
                                cb(res.data);
                            }
                        } else {
                            if (error_cb && typeof error_cb == 'function') {
                                error_cb(res.data);
                            }
                            lobby.instance?.showToast(res.message);
                        }
                    } else {
                        if (error_cb && typeof error_cb == 'function') {
                            error_cb(res.data);
                        } else {
                            lobby.instance?.showToast("请求失败");
                        }

                    }
                } catch (e) {
                    console.error(e);
                    if (error_cb) {
                        error_cb()
                    }
                }


            }
        };
        switch (type) {
            case "GET":
                xhr.send();
                break;
            case "POST":
                xhr.send(jsonData);
                break;
            default:
                xhr.send(jsonData);
                break;
        }



    }
    upLoadImg(imgPath: string) {
        return new Promise<any>((rs, rj) => {
            let xhr = new XMLHttpRequest();
            let formData = new FormData();
            formData.append('file', imgPath);
            xhr.open('POST', "http://116.62.119.201:3000/api/upload/album", true);
            xhr.setRequestHeader("Content-Type", "multipart/form-data;charset=UTF-8");

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                    try {
                        var res = JSON.parse(xhr.responseText);
                        // if (callback && typeof callback == 'function') {
                        let re = res.success ? res.data : res.message;
                        rs(re);
                        // }                        /* code */
                    } catch (e) {
                        console.log(e);
                    }
                }
            };
            xhr.send(JSON.stringify(imgPath));
        })
    }
}
interface ResultData {
    msg: string
    code: number
    data: any
}
export const http: HttpClient = HttpClient.getInstance();